<?php


namespace app\community\sms\lib;


use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class ali
{

    private array $config = [];

    /**
     * 阿里云发送短信
     * @param $to_phone | 需要接受短信的手机号
     * @param $send_data | 发送的内容
     * @param $config | 短信配置信息
     * @return bool
     * @throws ClientException
     */
    public function send_ali_sms($to_phone, $send_data, array $config = []) : bool
    {
        $this->config["TemplateCode"] = $TemplateCode ?? $this->config["TemplateCode"];

        AlibabaCloud::accessKeyClient($this->config['accessKeyId'], $this->config['accessSecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
            $options = [
                'query' => [
                    'RegionId' => $config['regionId'],
                    'PhoneNumbers' => $to_phone,
                    'SignName' => $config['SignName'],
                    'TemplateCode' => $config['TemplateCode'],
                ],
            ];
            $send_data = is_array($send_data) ? $send_data : [
                'code' => $send_data
            ];
            $options['query']['TemplateParam'] = json_encode($send_data, true);
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options($options)
                ->request();
            return $result->toArray()['Code'] == 'OK';
        } catch (ClientException | ServerException $e) {
            return false;
        }
    }

    /**
     * @param array $config
     * @return static
     */
    public function setConfig(array $config): static
    {
        $this->config = $config;
        return $this;
    }

}